import { dialog, ipcMain,BrowserWindow,shell } from "electron";
import { Share } from "./share";
import { MsgChannel } from "@common/constants";
import {createContextMenu} from './contentMenu'
import {log} from './logManager';
const getSysConfig = (): void => {
  ipcMain.on(MsgChannel.Config.GET, async (event) => {
    log.log(
      `收到渲染线程获取配置命令，返回值为：${JSON.stringify(Share.config)}`,
    );
    event.returnValue = Share.config;
  });

  ipcMain.on(MsgChannel.System.GET, async (event) => {
    event.returnValue = (Share as any).connectState;
  });
};

const listenEvents = (): void => {
  ipcMain.handle(MsgChannel.Folder.Select, async () => {
    const result = await dialog.showOpenDialog({
      title: "dicom-viewer",
      properties: ["openDirectory"],
    });
    if (result.canceled) {
      return null;
    }
    return result.filePaths[0];
  });

  ipcMain.handle(MsgChannel.SendSocketIo, async (_,msg) => {
    Share.imgSocketIo.sendMsg(msg);
  });

  ipcMain.handle(MsgChannel.Menu.showMenu, (event, menuType = '', data = '') => {
    const contextMenu = createContextMenu(menuType,data);
    contextMenu.popup({
      window: BrowserWindow.fromWebContents(event.sender) as any
    });
  });

  ipcMain.handle(MsgChannel.Folder.Open, async (_, folderPath: string) => {
    try {
      console.log(`mainThread ${folderPath}`);
      await shell.openPath(folderPath)
      return { success: true }
    } catch (error) {
      console.error('打开文件夹失败:', error)
      return { success: false, error: error}
    }
  })
};

export const initMainEventsListen = (): void => {
  getSysConfig();
  log.info('getSysConfig')
  listenEvents();
  log.info('listenEvents')
};
